package cm.word.generate.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 将oracle数据表，生成 word 表格
 *
 * @caomin
 * @create 2017-12-09 19:01
 **/
@Configuration
@MapperScan(basePackages = MysqlWordDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "mysqlWordSqlSessionFactory")
public class MysqlWordDataSourceConfig {

    // 精确到 cluster 目录，以便跟其他数据源隔离

    static final String PACKAGE = "cm.word.generate.dao.mysql";

    static final String MAPPER_LOCATION = "classpath:mapper/mysql/*.xml";

    @Value("${mysqlWord.jdbc.url}")
    private String dbUrl;

    @Value("${mysqlWord.jdbc.username}")
    private String username;

    @Value("${mysqlWord.jdbc.password}")
    private String password;


    @Bean(name = "mysqlWordDataSource")
    public DataSource clusterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(dbUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }


    @Bean(name = "mysqlWordTransactionManager")
    public DataSourceTransactionManager clusterTransactionManager() {

        return new DataSourceTransactionManager(clusterDataSource());

    }

    @Bean(name = "mysqlWordSqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("mysqlWordDataSource") DataSource clusterDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(clusterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MysqlWordDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();

    }

}
